module nazo.zlib;
/**
 * zlibを使ってgzip圧縮します。
 * History:
 *          0.0.0.1 バージョン付け開始
 * Authors: Nazo
 * Version: 0.0.0.1
 * License: Public Domain
 */
public import std.zlib;
import std.string, std.stdio;

version(USE_ZLIB){
  extern(C){
    extern int compress2(void* dest, uint* destLen,
                         const(void)* source, uint sourceLen, int level);
  }
  enum{
    Z_OK            =0,
    Z_STREAM_END    =1,
    Z_NEED_DICT     =2,
    Z_ERRNO        =-1,
    Z_STREAM_ERROR =-2,
    Z_DATA_ERROR   =-3,
    Z_MEM_ERROR    =-4,
    Z_BUF_ERROR    =-5,
    Z_VERSION_ERROR =-6,
  }
  void[] compress(const(void)[] srcbuf, int level=6){
    if(!srcbuf.length)return null;
    uint len=srcbuf.length + srcbuf.length/10/*cast(size_t)(srcbuf.length*1.1)*/ + 12;
    ubyte[] buf=new ubyte[len];
    int err=compress2(buf.ptr,&len,srcbuf.ptr,srcbuf.length, level);
    if(err!=Z_OK)throw new Exception("\n\nzlib err"~.toString(err));
    buf.length=len;
    return buf;
  }
  void compress(const(void)[] srcbuf, void delegate(const(void)[] buf) dg, int level=6){
    if(!srcbuf.length)return null;
    uint len=srcbuf.length + srcbuf.length/10/*cast(size_t)(srcbuf.length*1.1)*/ + 12;
    scope ubyte[] buf=new ubyte[len];
    int err=compress2(buf.ptr,&len,srcbuf.ptr,srcbuf.length, level);
    if(err!=Z_OK)throw new Exception("\n\nzlib err"~.toString(err));
    buf.length=len;
    dg(buf);
  }
}
